package com.example.demo.config;

import cn.hutool.json.JSONUtil;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

// redis存储会话ai聊天记录
@Component
public class RedisChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private RedisTemplate   redisTemplate;
    // 获取会话
    @Override
    public List<ChatMessage> getMessages(Object id) {
        Object o = redisTemplate.opsForValue().get(id);
        return ChatMessageDeserializer.messagesFromJson(o.toString());
    }
    // 更新会话
    @Override
    public void updateMessages(Object id, List<ChatMessage> list) {
        redisTemplate.opsForValue().set(ChatMessageSerializer.messagesToJson( list),list, TimeUnit.DAYS.toDays(7));
    }
    // 删除会话
    @Override
    public void deleteMessages(Object id) {
        redisTemplate.delete(id.toString());
    }
}
